import "./index.scss"

import React, { Component } from 'react'
import { ajax } from "../../api";
import {Table , Button, Tag,Form ,Input,Row,Col , Select,Modal,message,Popconfirm} from "antd"
import { roleList } from "../../utils";
import {observer} from "mobx-react"
import {reg} from "../../utils/validate"
import mobxdata from '../../mobx/data'
import moment from 'moment'
const {phone}  = reg;

const { Option } = Select;

class UserList extends Component {
    state = {
        list:[],
        columns:[
            {
                align:"center",
                title:"员工姓名",
                key:"username",
                dataIndex:"username"
            },
            {
                align:"center",
                title:"手机号码",
                key:"phone",
                dataIndex:"phone",
                render:(text,item)=>{

                    return text
                }
            },
            {
                align:"center",
                title:"年龄",
                key:"age",
                dataIndex:"age"
            },
            {
                align:"center",
                title:"性别",
                key:"sex",
                dataIndex:"sex"
            },
            {
                align:"center",
                title:"入职时间",
                key:"time",
                dataIndex:"time"
            },
            {
                align:"center",
                title:"员工职位",
                key:"role",
                dataIndex:"role",
                render:(text,a)=>{
                    
                    return (
                        <Tag style={{margin:"0 5px"}} color={  roleList.find(item=>item.role==text).color }> {roleList.find(item=>item.role==text).title }  </Tag>
                    )
                }
            },
            {
                align:"center",
                title:"操作",
                render:(text,item)=>{
                    const {userinfo } = mobxdata
                    return (
                        userinfo.role>item.role?<p>
                            <Popconfirm
                                        title="你确定要删除该员工吗?"
                                        onConfirm={()=>this.confirm(item)}
                                        onCancel={this.cancel}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <Button type="danger" disabled={userinfo.role>item.role?false:true}  style={{marginRight:6}} size="small">删除</Button>
                                    </Popconfirm>
                            <Button type="primary" onClick={()=>this.updateItem(item)} disabled={userinfo.role>item.role?false:true}    size="small">修改</Button>
                        </p>
                        :
                        <p>
                            暂无权限
                        </p>
                    )
                }
            },
        ],
        isModalVisible:false,
        updateVisible:false,
        item:{}
    }
    componentDidMount(){
        ajax.getuserlist()
        .then(res=>{
            if(res.code==200){
                console.log(res.result);
                res.result.forEach(item => {
                    item.time = moment(item.time).format('YYYY-MM-DD HH:MM:SS')
                });
                this.setState({
                    list:res.result
                })
            }
        })
    }
    confirm = (item)=>{
        ajax.deluserone({
            _id:item._id
        })
        .then(res=>{
            if(res.code==200){
                var list = this.state.list.filter(l=>l._id!=item._id)
                this.setState({
                    list
                })
            }
        })
    }
    cancel = ()=>{}
    startSearchData = (value)=>{
        console.log(value);
        ajax.getuserlist(value)
        .then(res=>{
            this.setState({
                list :res.result
            })
        })
    }
    resetSearchForm = ()=>{
        this.searchFrom.resetFields()
    }
    showAddModal = ()=>{
        this.setState({
            isModalVisible:true
        })
    }
    updateItem = (item)=>{
        this.setState({
            updateVisible:true,
            item
        })
        setTimeout(()=>{
            this.updateFrom.setFieldsValue(item)
        },1)
    }
    updatehandleOk = ()=>{
        this.updateFrom.validateFields()
        .then(value=>{
            ajax.updateuserone({
                _id:this.state.item._id,
                ...value
            }).then(res=>{
                if(res.code==200){
                    var list = this.state.list.map((item,i)=>{
                        if(item._id == this.state.item._id){
                            item = {...item,...value}
                        }
                        return item
                    })
                    this.setState({
                        list,
                        updateVisible:false
                    })
                }
            })
        })
    }
    updatehandleCancel = ()=>{
        this.setState({
            updateVisible:false
        })
    }
    handleCancel = ()=>{
        this.setState({
            isModalVisible:false
        })
    }
    handleOk = ()=>{
        this.addFrom.validateFields()
        .then(value=>{
            ajax.addusers(value)
            .then(res=>{
                if(res.code==200){
                    ajax.getuserlist()
                    .then(res=>{
                        if(res.code==200){
                            this.setState({
                                list:res.result,
                                isModalVisible:false
                            })
                        }
                    })
                }
            })
        })
    }
    donwloadExcel = (table,name)=>{
        if(this.state.list.length>0){
            var uri = 'data:application/vnd.ms-excel;base64,',
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
            format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };

            if (!table.nodeType) table = document.getElementById(table)
            var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }

            var filename = name+moment().format("L")+'.xls';
            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();
        }else{
            message.error("请等待数据载入后再导出")
        }
    }
    render(){
        const {userinfo} = mobxdata
        return(
            <div>
                {
                userinfo.role>=3&&
                <Button style={{marginBottom:'10px'}} type="danger"  onClick={this.showAddModal} >添加员工</Button>
                }
                <Form 
                    ref={el=>this.searchFrom=el}
                    onFinish={this.startSearchData}
                >
                    <Row>
                        <Col span={8} >
                            <Form.Item
                                label="员工姓名"
                                name="username"
                                
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                        <Col span={8} offset={4}>
                            <Form.Item
                                label="手机号码"
                                name="phone"
                                
                            >
                                <Input />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8} >
                            <Form.Item
                                label="员工职位"
                                name="role"
                            >   
                                <Select
                                    placeholder="请选择"
                                    onChange={this.onGenderChange}
                                    allowClear
                                    >
                                    {
                                        roleList.map((item,i)=>{
                                            return (
                                                <Option value={item.role} key={i} > {item.title}</Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={8} offset={4}>
                            <Form.Item >   
                                <Button type="primary"  htmlType="submit" style={{marginRight:6}}>搜索</Button>
                                <Button type="danger" style={{marginRight:6}} onClick={this.resetSearchForm}>重置</Button>
                                <Button onClick={()=>this.donwloadExcel("usertable",'用户列表')}>导出</Button>
                                <a id="dlink" style={{display:'none'}}></a>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
                <Table
                    id="usertable"
                    sticky
                    bordered
                    dataSource={this.state.list}
                    columns ={this.state.columns }
                    rowKey={
                        (item)=>item._id
                    }
                    pagination={{pageSize:5}}
                >

                </Table>
                <Modal 
                    title="修改员工个人信息" 
                    visible={this.state.updateVisible} 
                    onOk={this.updatehandleOk} 
                    onCancel={this.updatehandleCancel}
                    okText="确认修改"
                    cancelText="取消"
                    className="my-modal"
                    >
                    <Form 
                        ref={el=>this.updateFrom=el}
                        initialValues={{
                            password:"qwe123"
                        }}
                        layout="vertical"
                    >
                        
                            <Col span={20} >
                                <Form.Item
                                    label="员工姓名"
                                    name="username"
                                    rules={[
                                        { required: true, message: '请输入员工姓名' },
                                    
                                    ]}
                                >
                                    <Input 
                                        
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={20}>
                                <Form.Item
                                    label="手机号码"
                                    name="phone"
                                    rules={[{ required: true, message: '请输入手机号码' }, 
                                    {
                                        pattern:phone,message:'请输入正确格式的手机号码'
                                    }]}
                                >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={20} >
                                <Form.Item
                                    label="年龄"
                                    name="age"
                                    rules={[
                                        { required: true, message: '请输入员工年龄' },
                                    
                                    ]}
                                >
                                    <Input 
                                        
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={20} >
                                <Form.Item
                                    label="性别"
                                    name="sex"
                                    rules={[
                                        { required: true, message: '请输入员工年龄' },
                                    
                                    ]}
                                >
                                    <Input 
                                        
                                    />
                                </Form.Item>
                            </Col>
                            
                            <Col span={20} >
                                <Form.Item
                                    label="员工职位"
                                    name="role"
                                    rules={[{ required: true, message: '请选择' }]}
                                >   
                                    <Select
                                        placeholder="请选择"
                                        
                                        allowClear
                                        >
                                        {
                                            roleList.map((item,i)=>{
                                                return (
                                                    (userinfo.role>item.role)&&<Option value={item.role} key={i} > {item.title}</Option>
                                                )
                                            })
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                    </Form>
                </Modal>

                <Modal 
                    title="添加员工" 
                    visible={this.state.isModalVisible} 
                    onOk={this.handleOk} 
                    onCancel={this.handleCancel}
                    okText="确定"
                    cancelText="取消"
                    className="my-modal"
                    >
                    <Form 
                        ref={el=>this.addFrom=el}
                        onFinish={this.addUserData}
                        initialValues={{
                            password:"asd123"
                        }}
                        layout="vertical"
                    >
                        
                            <Col span={20} >
                                <Form.Item
                                    label="员工姓名"
                                    name="username"
                                    rules={[
                                        { required: true, message: '请输入员工姓名' },
                                    
                                    ]}
                                >
                                    <Input 
                                        
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={20}>
                                <Form.Item
                                    label="手机号码"
                                    name="phone"
                                    rules={[{ required: true, message: '请输入手机号码' }, 
                                    {
                                        pattern:phone,message:'请输入正确格式的手机号码'
                                    }]}
                                >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={20}>
                                <Form.Item
                                    label="登录密码"
                                    name="password"
                                    rules={[{ required: true, message: '请输入登录密码' }]}
                                >
                                    <Input/>
                                </Form.Item>
                            </Col>
                            <Col span={20} >
                                <Form.Item
                                    label="员工职位"
                                    name="role"
                                    rules={[{ required: true, message: '请选择' }]}
                                >   
                                    <Select
                                        placeholder="请选择"
                                        
                                        allowClear
                                        >
                                        {
                                            roleList.map((item,i)=>{
                                                return (
                                                    (userinfo.role>item.role)&&<Option value={item.role} key={i} > {item.title}</Option>
                                                )
                                            })
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                    </Form>
                </Modal>
                
            </div>
        )
    }

}
export default  UserList